package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.RoleDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service
public class RoleServiceImpl implements RoleService {



    //依赖注入RoleDao
    @Autowired
    private RoleDao roleDao;






    /*
     * 添加角色
     * */
    @Override
    public void add(Role role,Integer[] permissionIds) {

        //1.调用dao, 保存检查组基本信息
        roleDao.add(role);

        //2.调用dao, 向t_role_permission中间表保存所有的被勾选的权限
        for (Integer permissionId : permissionIds) {

            Map map = new HashMap();

            map.put("role_id",role.getId());
            map.put("permission_id",permissionId);

            roleDao.addRoleAndPermission(map);
        }



    }

    @Override
    public Role findById(Integer id) {

         return roleDao.findRoleById(id);
    }

    @Override
    public void edit(Role role,Integer[] permissionIds) {

        //调用dao,保存角色信息
        roleDao.edit(role);

        //调用dao,删除中间表t_role_permission中指定角色id的数据
        roleDao.deleteRoleAndPermission(role.getId());

        //调用dao,保存当前中间表中的数据
        for (Integer permissionId : permissionIds) {

            Map map  = new HashMap();
            map.put("role_id",role.getId());
            map.put("permission_id",permissionId);

            roleDao.addRoleAndPermission(map);
        }
    }

    /*
    * 删除角色功能: 先删除中间表数据,再删除角色数据
    * */
    @Override
    public void delById(Integer id) {

        //1.基于角色id查找t_role_permission中间表是否有数据, 如果有则删除
        if (roleDao.findPermissionIdsByRoleId(id)!=null){

            roleDao.deleteRoleAndPermission(id);
        }

        roleDao.delById(id);
    }


    /*
    * 编辑回显-权限复选框被勾选回显, 基于角色ID查找关联的权限集合
    * */
    @Override
    public List<Integer> findPermissionIdsByRoleId(Integer id) {


        List<Integer> permissionList = roleDao.findPermissionIdsByRoleId(id);
        System.out.println(">>>>>>>>权限列表为: "+permissionList.toArray().toString());
        return permissionList;

    }


    /*
    * 分页查询
    * */

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {

        //PageHelper工具启动,设置limit参数
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());

        //调用dao层方法
        Page<Role> page = roleDao.findRoleByCondition(queryPageBean.getQueryString());

        PageResult pageResult= new PageResult(page.getTotal(),page.getResult());

        return pageResult;
    }
}
